/**
 * Main_ContentPanel.java
 *
 * @author Evan Nelson
 */

package gui;

import java.awt.Color;
import java.awt.ComponentOrientation;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Stack;

import javax.swing.JButton;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;

import database.DB_connection;

/**
 * This is the main window for all GUI components to sit in.  
 * It's created on startup.
 */
public class Main_ContentPanel extends JPanel {

	/**
	 * 
	 */
	private static final long serialVersionUID = -1048760654538067390L;

	final boolean RIGHT_TO_LEFT = false;
	
	private DB_connection conn;
	
	private int windowHeight;
	private int windowWidth;
	
	private Dimension contentSize = new Dimension(600,500);

	private Stack<Container> contentStack;
	
    //Containers
	private Container navPanel;
    
    //Buttons
    private JButton weightliftingButton;
    private JButton enduranceButton;
    private JButton curButton;
    
    private Color normalButtonColor = new JButton().getBackground();
    private Color activeButtonColor = new Color(200, 200, 200, 255);
    
    //Labels
    JLabel fillerLabel;
    JLabel sqlLabel;
    
    //Textfields
    JTextField sqlField;

    //Menu items
    public JCheckBoxMenuItem expertMode;
    
    /**
     * Build a menu to match this content pane
     */
    public JMenuBar generateMenu() {
		JMenuBar bar = new JMenuBar();
		
		JMenu menu = new JMenu("File");
		menu.setMnemonic(KeyEvent.VK_F);
		
		JMenuItem about = new JMenuItem("About");
		about.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				JOptionPane.showMessageDialog(Main_ContentPanel.this, "This is where we would tell you about us, if we wanted to.");
			}
		});
		menu.add(about);
		
		JMenuItem quit = new JMenuItem("Quit");
		quit.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				System.exit(0);
			}
		});
		menu.add(quit);
		
		bar.add(menu);
		
	    menu = new JMenu("Options");
	    menu.setMnemonic(KeyEvent.VK_O);
	    
	    expertMode = new JCheckBoxMenuItem("Expert mode");
	    expertMode.addItemListener(new ItemListener() {
	    	public void itemStateChanged(ItemEvent e) {
	    		if(expertMode.isSelected()) {
	    			sqlLabel.setVisible(true);
	    			sqlField.setVisible(true);
	    		} else {
	    			sqlLabel.setVisible(false);
	    			sqlField.setVisible(false);
	    		}
	        }
	    });
	    menu.add(expertMode);
	    
	    bar.add(menu);
	    return bar;
    }
    
	/**
     * Add individual panels to the main panel
     */
    public void addComponentsToPane() {
		if (RIGHT_TO_LEFT) {
			setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
		}
		
		setLayout(new GridBagLayout());
		GridBagConstraints c = new GridBagConstraints();
		
		//make all components as tall as the window itself,
		//and fill their respective columns
		c.ipady = this.windowHeight;
		c.fill = GridBagConstraints.HORIZONTAL;
		
		//add nav panel
		navPanel = new JPanel();
		addNavComponentsToPane(navPanel);
		c.weightx = 0.12;
		c.gridx = 0;
		c.gridy = 0;
		add(new JScrollPane(navPanel), c);
		
		//add empty placeholder panel
		//JPanel placeholder = new JPanel();
		//placeholder.setSize(this.contentSize);
		//replaceCurrentContent(placeholder);
		
		//Content_GraphingPane graphPanel = new Content_GraphingPane(this.contentSize);
		Content_WeightliftingChart wPane = new Content_WeightliftingChart(false, this.contentSize);
		replaceCurrentContent(new JScrollPane(wPane));
		
	}//end addComponentsToPane
    
    
    /**
     * Add components to the navigation pane
     */
	private void addNavComponentsToPane(Container pane) {
		if (RIGHT_TO_LEFT) {
			navPanel.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
		}
		
		navPanel.setLayout(new GridBagLayout());
		GridBagConstraints c = new GridBagConstraints();
		
		c.fill = GridBagConstraints.HORIZONTAL;
		c.gridx = 0;
		c.weightx = 1.0;

		sqlLabel = new JLabel("Direct SQL Query Box");
		sqlLabel.setVisible(false);
		c.gridy = 0;
		pane.add(sqlLabel, c);
		
		sqlField = new JTextField();
		sqlField.setVisible(false);
		sqlField.addKeyListener(new KeyListener() {
			public void keyPressed(KeyEvent keyEvent) {}
		    public void keyReleased(KeyEvent keyEvent) {}
		    public void keyTyped(KeyEvent e) {
		        if(e.getKeyChar() == KeyEvent.VK_ENTER) {
		        	executeSQL(sqlField.getText());
		        }
		    }
		});
		c.gridy = 1;
		pane.add(sqlField, c);
		
		JLabel header = new JLabel("Header1");
		c.insets = new Insets(10,0,0,0);
		c.gridy = 5;
		//pane.add(header, c);
		c.insets = new Insets(0,0,0,0);
		
		header = new JLabel("Weightlifting");
		c.insets = new Insets(10,0,0,0);
		c.gridy = 10;
		pane.add(header, c);
		c.insets = new Insets(0,0,0,0);
		
		weightliftingButton = new JButton("Weightlifting Chart");
		weightliftingButton.setBackground(activeButtonColor);
		curButton = weightliftingButton;
		weightliftingButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				weightliftingChartButtonActionPerformed(evt);
			}
		});
		c.gridy = 11;
		pane.add(weightliftingButton, c);
		
		weightliftingButton = new JButton("Weightlifting Log");
		weightliftingButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				weightliftingLogButtonActionPerformed(evt);
			}
		});
		c.gridy = 12;
		pane.add(weightliftingButton, c);
		 
		weightliftingButton = new JButton("Weightlifting Graphs");
		weightliftingButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				weightliftingGraphButtonActionPerformed(evt);
			}
		});
		c.gridy = 13;
		pane.add(weightliftingButton, c);
		
		header = new JLabel("Endurance");
		c.insets = new Insets(10,0,0,0);
		c.gridy = 20;
		pane.add(header, c);
		c.insets = new Insets(0,0,0,0);
		
		enduranceButton = new JButton("Endurance Chart");
		enduranceButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				enduranceChartButtonActionPerformed(evt);
			}
		});
		c.gridy = 21;
		pane.add(enduranceButton, c);
		
		enduranceButton = new JButton("Endurance Log");
		enduranceButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				enduranceLogButtonActionPerformed(evt);
			}
		});
		c.gridy = 22;
		pane.add(enduranceButton, c);
		
		for(int i = 0; i < 16; i++) {
			fillerLabel = new JLabel(" ");
			c.gridy = GridBagConstraints.RELATIVE;
			pane.add(fillerLabel,c);
		}
	}
     
     /**
      * This method wipes out all the old content panes that were currently
      * in use and replaces them with a new panel.
      */
     private void replaceCurrentContent(Container newPanel) {
    	 //newPanel.setSize(this.contentSize);
    	 //JScrollPane scrollablePane = new JScrollPane(newPanel);

    	 while(!contentStack.empty()) {
    		 System.out.print("Popping something off the stack:");
    		 Container c = contentStack.pop();
    		 System.out.println(c.getClass());
        	 remove(c);
         }
         
         GridBagConstraints c = new GridBagConstraints();
         c.ipady = this.windowHeight;
         c.fill = GridBagConstraints.HORIZONTAL;
         c.weightx = 0.5;
         c.gridx = 1;
         c.gridy = 0;
         add(newPanel, c);
         contentStack.push(newPanel);
         
         updateUI();
     }
     
     /**
      * @param evt
      */
     private void weightliftingChartButtonActionPerformed(java.awt.event.ActionEvent evt) {
    	 ((JButton)evt.getSource()).setBackground(activeButtonColor);
    	 curButton.setBackground(normalButtonColor);
    	 curButton = ((JButton)evt.getSource());
    	 
    	 System.out.println("Loading weightlifting GUI with editting=false");  
    	 Content_WeightliftingChart wChart = new Content_WeightliftingChart(false, this.contentSize);
         replaceCurrentContent(new JScrollPane(wChart));
     }
     
     /**
      * @param evt
      */
     private void weightliftingLogButtonActionPerformed(java.awt.event.ActionEvent evt) {  
    	 ((JButton)evt.getSource()).setBackground(activeButtonColor);
    	 curButton.setBackground(normalButtonColor);
    	 curButton = ((JButton)evt.getSource());
    	                                                 
    	 System.out.println("Loading weightlifting GUI with editting=true");  
    	 Content_WeightliftingChart wChart = new Content_WeightliftingChart(true, this.contentSize);
         replaceCurrentContent(new JScrollPane(wChart));                
     }  
     
     /**
      * @param evt
      */
     private void weightliftingGraphButtonActionPerformed(java.awt.event.ActionEvent evt) {  
    	 ((JButton)evt.getSource()).setBackground(activeButtonColor);
    	 curButton.setBackground(normalButtonColor);
    	 curButton = ((JButton)evt.getSource());
    	                                                 
    	 System.out.println("Loading weightlifting graph");  
    	 Content_GraphingPane graph = new Content_GraphingPane(this.contentSize);
         replaceCurrentContent(new JScrollPane(graph));                
     }  
     
     /**
      * @param evt
      */
     private void enduranceChartButtonActionPerformed(java.awt.event.ActionEvent evt) {     
    	 ((JButton)evt.getSource()).setBackground(activeButtonColor);
    	 curButton.setBackground(normalButtonColor);
    	 curButton = ((JButton)evt.getSource());
    	                                              
         System.out.println("Loading endurance GUI with editting=false");  
         //TODO make this GUI
 		//enduranceChartGUI eChart = new enduranceChartGUI(false);
                        
     }   
     
     /**
      * @param evt
      */
     private void enduranceLogButtonActionPerformed(java.awt.event.ActionEvent evt) {     
    	 ((JButton)evt.getSource()).setBackground(activeButtonColor);
    	 curButton.setBackground(normalButtonColor);
    	 curButton = ((JButton)evt.getSource());
    	                                              
         System.out.println("Loading endurance GUI with editting=true");  
         //TODO make this GUI
 		//enduranceChartGUI eChart = new enduranceChartGUI(true);
                        
     }   
    
     public boolean executeSQL(String sql) {
    	 sql = sql.trim();
    	 
    	 conn = new DB_connection();
    	 String results = new String();
    	 
    	 String firstWord = sql.split("\\s+")[0];
    	 
    	 if(firstWord.toUpperCase().equals("SELECT")) {
	    	 System.out.println("Attempting to execute SQL: " + sql);
	    	 ResultSet rs = conn.executeCurrentStatement(sql);
	    	 if(rs == null) {
	    		 return false;
	    	 }
	    	 
	    	 try {
	    		 //figure out how many columns came back
	    		 int columns = rs.getMetaData().getColumnCount();
	    		 
	    		 while(rs.next()) {
	    			 for(int i = 1; i <= columns; i++) {
	    				 results += rs.getString(i) + " --- ";
	    			 }
	    			 results += "\n";
	    		 }
	    		 JOptionPane.showMessageDialog(Main_ContentPanel.this, results, "Results of query", JOptionPane.INFORMATION_MESSAGE);
	    	 } catch (SQLException e) {
	    		 System.err.println(e.getMessage());
	    		 return false;
	    	 }
    	 } else if(firstWord.toUpperCase().equals("UPDATE") 
    			 || firstWord.toUpperCase().equals("DELETE")
    			 || firstWord.toUpperCase().equals("INSERT")) {
    		 
    		 int sure = JOptionPane.showConfirmDialog(Main_ContentPanel.this, "Are you sure you want to execute this " + firstWord.toUpperCase() + " statement?\n   " + sql + "\nThis could corrupt your data!", "Are you sure?", JOptionPane.YES_NO_OPTION);
    		 if(sure != JOptionPane.YES_OPTION) {
    			 return false;
    		 }
    		 
	    	 System.out.println("Attempting to execute SQL: " + sql);
	    	 int rowsAffected = conn.executeCurrentUpdate(sql);
	    	 if(rowsAffected >= 0) {
	    		 JOptionPane.showMessageDialog(Main_ContentPanel.this, String.valueOf(rowsAffected) + " row(s) affected.", "Results of " + firstWord.toUpperCase() , JOptionPane.INFORMATION_MESSAGE);
	    	 }
    	 }
    	 
    	 return true;
     }
     
     public Main_ContentPanel(Dimension size) {
    	 this.windowHeight = size.height;
    	 this.windowWidth = size.width;
    	 
    	 setSize(size);
    	 
    	 //set up the content pane stack
    	 contentStack = new Stack<Container>();
     	
    	 //Add cPane to the contentPane
    	 addComponentsToPane();
     }      
   
}
